package com.bang.study.aggs;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.avg.InternalAvg;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @ClassName: ConstantScoreFilterAggs
 * @author: BANG
 * @Date: 2020/01/15 16:29
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 *GET /tvs/sales/_search
 * {
 *   "size": 0,
 *   "aggs": {
 *     "group_by_color": {
 *       "terms": {
 *         "field": "color",
 *         "order": {
 *           "avg_price": "desc"
 *         }
 *       },
 *       "aggs": {
 *         "avg_price": {
 *           "avg": {
 *             "field": "price"
 *           }
 *         }
 *       }
 *     }
 *   }
 * }
 */
public class OrderDescAggs {

    public static void main(String[] args) throws UnknownHostException {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        SearchResponse searchResponse = client.prepareSearch("tvs").setTypes("sales")
                .addAggregation(AggregationBuilders.terms("group_by_color").field("color")
                        .subAggregation(AggregationBuilders.avg("avg_price").field("price"))
                        .order(Terms.Order.aggregation("avg_price", false)))
                .setSize(0)
                .get();

        StringTerms group_by_color = searchResponse.getAggregations().get("group_by_color");
        List<Terms.Bucket> buckets = group_by_color.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            InternalAvg avg_price = bucket.getAggregations().get("avg_price");
            System.err.println("avg_price: "+avg_price.getValueAsString());
        }
        client.close();

    }
}
